package com.example.indenture.team.service.impl;

import com.example.indenture.common.vo.Result;
import com.example.indenture.common.vo.Search;
import com.example.indenture.race.dao.RaceDao;
import com.example.indenture.team.dao.TeamDao;
import com.example.indenture.team.entity.Team;
import com.example.indenture.team.service.TeamService;
import com.example.indenture.user.dao.UserDao;
import com.example.indenture.util.VerificationCodeGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class TeamServiceImpl implements TeamService {
    @Autowired
    private TeamDao teamDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RaceDao raceDao;

    @Override
    @Transactional
    public Result<Team> insertTeam(Team team) {
        if (team == null) {
            return Result.failed("队伍异常!");
        } else if (teamDao.getTeamByName(team.getName()) != null) {
            return Result.failed("队伍名重复！");
        }
        team.setCreateDate(LocalDateTime.now());
        team.setUpdateTime(LocalDateTime.now());
        team.setVercode(VerificationCodeGenerator.generateCode());
        //判断该lid用户是否已经在该rid的比赛中加入了队伍
        List<Integer> list = teamDao.isInTeam(team.getLid(), team.getRid());
        for (int id : list) {
            if (id == team.getRid()) {
                return Result.failed("该成员已经参加了队伍！");
            }
        }
        try {

            //新增队伍表的数据
            teamDao.insertTeam(team);
            System.out.println(team);
            //新增team_user表中的关系
            teamDao.addTeamUser(team.getLid(), team.getId(), team.getRid());
        } catch (Exception e) {
            return Result.failed("新增队伍失败！");
        }
        return Result.ok(team);
    }

    @Override
    @Transactional
    public Result<Object> deleteTeam(Integer tid) {
        if (tid == null) {
            return Result.failed("删除队伍异常!");
        }
        try {
            //新增team_user表中的关系
            teamDao.deleteTeamUser(tid);
            //删除队伍表的数据
            teamDao.deleteTeam(tid);
        } catch (Exception e) {
            return Result.failed("删除队伍失败！");
        }
        return Result.ok("删除队伍成功!");
    }

    @Override
    public Result<Object> updateTeam(Team team) {
        Team temp = teamDao.getTeamByName(team.getName());
        if (temp != null && temp.getId() != team.getId()) {
            return Result.failed("该队伍名已存在！");
        }
        try {
            // 初始化 user 相关属性
            team.setUpdateTime(LocalDateTime.now());
            // 进行更新操作
            teamDao.updateTeam(team);
        } catch (Exception e) {
            return Result.failed("删除队伍失败！");
        }
        return Result.ok(team);
    }

    @Override
    public PageInfo<Team> teamByRaceAndName(Integer rid, Search search) {
        search.initSearch();
        PageHelper.startPage(search.getCurrentPage(), search.getPageSize());
        List<Team> teamList = teamDao.teamByRaceAndName(rid, search);
        for (Team team : teamList) {
            team.setLeader(userDao.getUserById(team.getLid()));
            team.setRace(raceDao.getRaceById(team.getRid()));
            team.setUserNum(teamDao.getTeamUserNum(team.getId()));
        }
        return new PageInfo<>(Optional
                .ofNullable(teamList)
                .orElse(Collections.emptyList()));
    }

    @Override
    public Result<Object> addTeamUser(Integer uid, Integer tid, Integer rid) {
        List<Integer> list = teamDao.isInTeam(uid, rid);
        for (int id : list) {
            if (id == rid) {
                return Result.failed("该成员已经参加了队伍！");
            }
        }
        teamDao.addTeamUser(uid, tid, rid);
        return Result.ok("恭喜加入队伍成功!");
//        System.out.println(teamDao.getVercodeById(tid));
//
//        if (teamDao.getVercodeById(tid).getVercode().equals(vercode) == true) {
//            try {
//                teamDao.addTeamUser(uid, tid, rid);
//                return Result.ok("恭喜加入队伍成功!");
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//        } else {
//            return Result.failed("验证码错误!");
//        }

    }

    @Override
    public Result<Object> quitTeam(Integer tid, Integer uid) {
        try {
            teamDao.quitTeam(tid, uid);
        } catch (Exception e) {
            return Result.failed("退出队伍失败！");
        }
        return Result.ok("退出队伍成功！");
    }


    @Override
    public Result<List<Team>> teamListByUser(Integer uid) {
        List<Team> teamList = null;
        try {
            teamList = teamDao.teamListByUser(uid);
            for (Team team : teamList) {
                team.setLeader(userDao.getUserById(team.getLid()));
                team.setRace(raceDao.getRaceById(team.getRid()));
                team.setUserNum(teamDao.getTeamUserNum(team.getId()));
            }
        } catch (Exception e) {
            return Result.failed("获取队伍列表失败！");
        }
        return Result.ok(teamList);
    }

    @Override
    public Result<Object> isInTeam(Integer uid, Integer rid) {
        //判断该lid用户是否已经在该rid的比赛中加入了队伍
        List<Integer> list = teamDao.isInTeam(uid, rid);
        for (int id : list) {
            if (id == rid) {
                return Result.failed("该成员已经参加了队伍！");
            }
        }
        return Result.ok();
    }

    @Override
    public Team getTeamByVercode(Integer vercode) {
        return teamDao.getTeamByVercode(vercode);
    }

    @Override
    public Team ok(Integer vercode,Integer tid) {
        return teamDao.ok(vercode,tid);
    }

    @Override
    public Team findById(Integer id) {
        return teamDao.findById(id);
    }
}
